<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>minio文件服务</title>
    <script th:src="@{/static/js/axios.min.js}"></script>
    <script th:src="@{/static/js/jQuery.min.js}"></script>
    <!--引入 element-ui 的样式，-->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 必须先引入vue，  后使用element-ui -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <!-- 引入element 的组件库-->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

</head>
<body>
<div id="app">

    <!--    <el-progress type="circle" :percentage="num"></el-progress>-->
    <!--    <el-progress type="circle" :percentage="num" status="success"></el-progress>-->
    <!--    <el-progress type="circle" :percentage="num" status="warning"></el-progress>-->

    <h1>springboot minio 文件存储服务</h1>
    <!--    <el-row>-->
    <!--        <el-col :span="12">-->
    <!--        </el-col>-->
    <!--        <el-col :span="12">-->
    <!--        </el-col>-->
    <!--    </el-row>-->
    <el-input v-model="uploadData.bucketName" style="width: 500px;">
        <template slot="prepend">桶名称</template>
    </el-input>
    <el-input v-model="uploadData.folderName" style="width: 500px;">
        <template slot="prepend">文件夹(多层使用/分割)</template>
    </el-input>
    <el-upload
            ref="upload"
            class="upload-demo"
            action="file/uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :data="uploadData"
            multiple
            drag
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">上传文件，且不超过500M</div>
    </el-upload>
    <el-select v-model="selectBucketName" placeholder="请选择桶名称" @change="getFileList">
        <el-option
                v-for="item in bucketNames"
                :key="item"
                :label="item"
                :value="item">
        </el-option>
    </el-select>
    <el-button type="primary" class="el-icon-refresh" @click="getBucketNames">获取桶信息({{bucketNames.length}})</el-button>
    <el-button type="success" class="el-icon-refresh" @click="getFileList">获取文件信息({{fileList.length}})</el-button>
    <el-button type="info" class="el-icon-download" @click="batchDownload">批量下载</el-button>
    <el-button type="danger" class="el-icon-delete" @click="batchDelete">批量删除</el-button>
    <span>选中{{multipleSelection.length}}个文件</span>
    <div>
        <template>
            <el-table
                    :data="fileList"
                    empty-text="暂无数据"
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="bucketName"
                        label="桶名"
                        align="left"
                        min-width="300">
                </el-table-column>
                <el-table-column
                        prop="folderName"
                        label="文件夹"
                        align="left"
                        min-width="300">
                </el-table-column>
                <el-table-column
                        prop="fileName"
                        label="文件名"
                        align="left"
                        min-width="300">
                </el-table-column>
                <el-table-column
                        prop="uploadTime"
                        label="上传时间"
                        align="left"
                        min-width="300">
                </el-table-column>
                <el-table-column label="操作" fixed="left" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button @click="getPreview(scope.row)" type="text" size="small">查看</el-button>
                        <el-button @click="download(scope.row)" type="text" size="small">下载</el-button>
                        <el-button @click="deleteFile(scope.row)" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </div>


    <el-dialog
            title="预览"
            :visible.sync="dialogVisible"
            width="30%">
        <image v-if="previewSrc" :src="previewSrc"></image>
        <span slot="footer" class="dialog-footer">
<!--            <el-button @click="dialogVisible = false">取 消</el-button>-->
            <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
        </span>
    </el-dialog>

</div>

<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                visible: false,
                num: 0,
                // 文件列表信息
                fileList: [],
                // 上传额外参数
                uploadData: {
                    bucketName: "minio-demo-01",
                    folderName: "fileDisk"
                },
                //预览地址
                previewSrc: "",
                // 预览弹窗
                dialogVisible: false,
                // 选中数据
                multipleSelection: [],
                // 桶信息
                bucketNames: [],
                // 默认查询全部文件
                selectBucketName: "全部",
            }
        },
        created() {
            // this.fun();
            this.getBucketNames();
            this.getFileList();
        },
        methods: {
            fun() {
                if (this.num >= 100) return
                setTimeout(() => {
                    this.num += 20
                    this.fun()
                }, 1000)
            },
            // 数据选中事件
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 获取桶信息
            getBucketNames() {
                let self = this;
                axios({
                    method: 'get',//提交方法
                    url: '/file/listBuckets',//提交地址
                    params: {}
                }).then((res) => {
                    var data = res.data;
                    var arr = ["全部"];
                    data.data.forEach(item => {
                        arr.push(item);
                    });
                    self.bucketNames = arr;
                    self.$message.success('桶信息查询成功！');
                })
            },
            // 获取文件列表
            getFileList() {
                let self = this;
                var url = "/file/listAllFile";
                var params = {};
                if ("全部" != self.selectBucketName) {
                    url = "/file/listFiles";
                    params = {
                        "bucketName": self.selectBucketName
                    };
                }
                axios({
                    method: 'get',//提交方法
                    url: url,//提交地址
                    params: params,
                }).then((res) => {
                    console.log(res.data);
                    var data = res.data;
                    if (data && data.data.length > 0) {
                        self.fileList = data.data;
                        self.$message.success('文件查询成功！');
                    } else {
                        self.$message.success('文件查询成功,暂无数据！');
                    }
                })
            },
            // 文件预览
            getPreview(row) {
                let self = this;
                axios({
                    method: 'get',//提交方法
                    url: '/file/getPresignedObjectUrl',//提交地址
                    params: {
                        "bucketName": row.bucketName,
                        "fileName": row.filePath,
                        "expires": "1",
                    }
                }).then((res) => {
                    console.log(res.data);
                    var data = res.data;
                    if (data.data) {
                        self.previewSrc = data.data;
                        self.dialogVisible = true;
                        self.$message.success('预览成功！');
                    } else {
                        self.$message.success('预览失败！');
                    }
                })
            },
            // 文件单个下载
            download(row) {
                window.location.href = `/file/downloadFile?bucketName=${row.bucketName}&fileName=${row.filePath}`;
            },
            // 文件批量下载
            batchDownload() {
                if (this.multipleSelection.length === 0) {
                    this.$message.error("未选择数据");
                    return;
                }
                var fileNames = [];
                var bucketNames = [];
                this.multipleSelection.forEach(e => {
                    bucketNames.push(`${e.bucketName}`);
                    fileNames.push(`${e.filePath}`);
                });
                window.location.href = `/file/batchDownloadFile?fileNames=${fileNames.join(",")}&bucketNames=${bucketNames.join(",")}`;
                // 下载zip文件名
                // var zipName = new Date().getTime();
                // window.location.href = `/file/batchDownloadFile?fileNames=${fileNames}&zipName=${zipName}`;
            },
            // 删除
            deleteFile(row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let self = this;
                    axios({
                        method: 'get',//提交方法
                        url: '/file/deleteFile',//提交地址
                        params: {
                            "bucketName": row.bucketName,
                            "fileName": row.filePath,
                        }
                    }).then((res) => {
                        console.log(res.data);
                        var data = res.data;
                        if (data.code == 200) {
                            self.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            self.getFileList();
                        } else {
                            self.$message.error('删除失败！');
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            // 批量删除
            batchDelete() {
                if (this.multipleSelection.length === 0) {
                    this.$message.error("未选择数据");
                    return;
                }
                var fileNames = [];
                var bucketNames = [];
                this.multipleSelection.forEach(e => {
                    bucketNames.push(`${e.bucketName}`);
                    fileNames.push(`${e.filePath}`);
                });
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let self = this;
                    axios({
                        method: 'get',//提交方法
                        url: '/file/batchDeleteFile',//提交地址
                        params: {
                            "bucketNames": bucketNames.join(","),
                            "fileNames": fileNames.join(","),
                        }
                    }).then((res) => {
                        console.log(res.data);
                        var data = res.data;
                        if (data.code == 200) {
                            self.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            self.getFileList();
                        } else {
                            self.$message.error('删除失败！');
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                let self = this;
                axios({
                    method: 'get',//提交方法
                    url: '/file/getPresignedObjectUrl',//提交地址
                    params: {
                        "bucket": self.uploadData.bucket,
                        "fileName": row.fileName,
                        "expires": "10000",
                    }
                }).then((res) => {
                    console.log(res.data);
                    var data = res.data;
                    if (data.data) {
                        self.previewSrc = data.data;
                        self.dialogVisible = true;
                        self.$message.success('预览成功！');
                    } else {
                        self.$message.error('预览失败！');
                    }
                })
            },
            // 上传相关函数
            // 文件列表移除文件时的钩子
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            // 点击文件列表中已上传的文件时的钩子
            handlePreview(file) {
                console.log(file);
            },
            // 文件超出个数限制时的钩子
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            // 上传成功
            handleAvatarSuccess(response, file, fileList) {
                // this.imageUrl = URL.createObjectURL(file.raw);
                this.$refs.upload.clearFiles();
                this.fileList = [];
                this.getFileList();
                this.$message.success('上传成功！');
            },
            // 上传成功
            handleAvatarError(response, file, fileList) {
                this.$message.error('上传十失败！');
            },
            // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传
            beforeAvatarUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                // const isLt2M = file.size / 1024 / 1024 < 2;
                //
                // if (!isJPG) {
                //     this.$message.error('上传头像图片只能是 JPG 格式!');
                // }
                // if (!isLt2M) {
                //     this.$message.error('上传头像图片大小不能超过 2MB!');
                // }
                return true;
            },
            // 上传相关函数
        }
    })
</script>
</body>
</html>

